from selenium.common import StaleElementReferenceException, TimeoutException, NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
# import pages.webpage
import webpage
from logs.logger import log
import pytest
import sys
from pathlib import Path
ROOT_DIR = Path(__file__).parent.parent  # 向上两级到 pom 目录
sys.path.append(str(ROOT_DIR))  # 添加到 Python 的模块搜索路径
from config.conf import cm


class BackupPage(webpage.WebPage):
    url = "https://47.122.30.27:33023/5f40ca64"
    # 页面元素定位器
    advanced_btn_locator = (By.XPATH, "/html/body/div/div[2]/button[3]")
    proceed_link_locator = (By.XPATH, "/html/body/div/div[3]/p[2]/a")
    username_locator = (By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[1]/div/input")
    password_locator = (By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[2]/div/input")
    login_btn_locator = (By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[5]/div/button")
    database_tab_locator = (By.XPATH, "/html/body/section/aside/section/div[2]/div/div/div[1]/div/ul/li[4]/a/span")
    backup_btn_locator = (By.XPATH,
                          "/html/body/section/section/section/div[1]/div/div[2]/div[2]/div/div/div[2]/div/div["
                          "2]/div/div[3]/table/tbody/tr[2]/td[6]/div/div/div/span[1]")
    # backup_btn_locator = (By.XPATH, '//span[contains(text(), "备份")]')
    download_btn_locator = (By.XPATH,
                            "/html/body/div[3]/div/div[2]/div[2]/div/div[1]/div/div[2]/div[1]/div/div[2]/div/div["
                            "4]/div[2]/table/tbody/tr[1]/td[7]/div/div/div/span[2]")

    # download_btn_locator = (By.XPATH, '//span[contains(text(), "下载")]')

    # 登录
    def login(self, username, password):
        """登录操作"""
        self.is_click(self.advanced_btn_locator)
        self.is_click(self.proceed_link_locator)
        self.input_text(self.username_locator, username)
        self.input_text(self.password_locator, password)
        self.is_click(self.login_btn_locator)

    def navigate_to_database(self):
        """进入数据库页面"""
        self.is_click(self.database_tab_locator)

    #  备份下载方法
    def method_backup_download(self, locator, msg):
        max_retries = 3
        for attempt in range(max_retries):
            try:
                print(f"尝试第 {attempt + 1} 次...")

                # 等待元素存在且可点击
                btn = WebDriverWait(self.driver, 15).until(
                    EC.presence_of_element_located(locator)
                )
                WebDriverWait(self.driver, 5).until(
                    EC.element_to_be_clickable(btn)
                ).click()

                print(f"✅ {msg}成功")
                log.info("点击元素：{}".format(locator))

                return True

            except StaleElementReferenceException:
                print("⚠️ 元素失效，自动重试...")
                continue

            except Exception as e:
                print(f"❌ 第 {attempt + 1} 次失败:", str(e))

        raise Exception(f"无法完成{msg}，已重试 {max_retries} 次")

    def backup_database(self):
        """带自动恢复的备份操作"""
        # max_retries = 3
        # for attempt in range(max_retries):
        #     try:
        #         print(f"尝试第 {attempt + 1} 次...")
        #
        #         # 等待元素存在且可点击
        #         btn = WebDriverWait(self.driver, 15).until(
        #             EC.presence_of_element_located(self.backup_btn_locator)
        #         )
        #         WebDriverWait(self.driver, 5).until(
        #             EC.element_to_be_clickable(btn)
        #         ).click()
        #
        #         print("✅ 备份成功")
        #         return True
        #
        #     except StaleElementReferenceException:
        #         print("⚠️ 元素失效，自动重试...")
        #         continue
        #
        #     except Exception as e:
        #         print(f"❌ 第 {attempt + 1} 次失败:", str(e))
        #
        # raise Exception(f"无法完成备份，已重试 {max_retries} 次")
        try:
            return self.method_backup_download(self.backup_btn_locator, "备份")
        except TimeoutException:
            raise Exception("备份按钮未找到，请检查页面是否加载完成")
        except NoSuchElementException:
            raise Exception("备份按钮定位器已失效，请更新定位器")
        except Exception as e:
            raise Exception(f"未知错误: {str(e)}")

    def download_backup(self):
        """点击下载备份"""
        # self.is_click(self.download_btn_locator)
        # assert self.element_text(self.download_btn_locator) == "下载"
        # print("下载完成")
        # max_retries = 3
        # for attempt in range(max_retries):
        #     try:
        #         print(f"尝试第 {attempt + 1} 次...")
        #
        #         # 等待元素存在且可点击
        #         btn = WebDriverWait(self.driver, 15).until(
        #             EC.presence_of_element_located(self.download_btn_locator)
        #         )
        #         WebDriverWait(self.driver, 5).until(
        #             EC.element_to_be_clickable(btn)
        #         ).click()
        #
        #         print("✅ 下载成功")
        #         return True
        #
        #     except StaleElementReferenceException:
        #         print("⚠️ 元素失效，自动重试...")
        #         continue
        #
        #     except Exception as e:
        #         print(f"❌ 第 {attempt + 1} 次失败:", str(e))
        #
        # raise Exception(f"无法完成下载，已重试 {max_retries} 次")
        return self.method_backup_download(self.download_btn_locator, "下载")


if __name__ == '__main__':
    from utils.browser_utils import init_chrome_browser
    from config.constants import chrome_path, driver_path

    # 初始化浏览器
    driver = init_chrome_browser(chrome_path, driver_path, detach=True)
    backup_page = BackupPage(driver)

    # 打开页面
    backup_page.get_url(backup_page.url)

    # 登录
    backup_page.login("8codkm1r", "69a377d2")

    # 进入数据库页面
    backup_page.navigate_to_database()

    # 备份数据库
    backup_page.backup_database()

    # 下载备份
    backup_page.download_backup()
